<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\RedisAdmin;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Log;
use think\Request;

class Province extends Backend
{
    protected $user_id = 0;  //用户id
    protected $school_id = 0; //学校id
    protected $city_model = ''; //学校id
    protected $city_region_model = ''; //学校id

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
     //   $this->Collegial_model = new \app\admin\model\member\Collegial();
        $this->model = new \app\admin\model\Province();
        $this->city_model = new \app\admin\model\ProvinceCity();
        $this->city_region_model = new \app\admin\model\ProvinceCityRegion();
      //  $this->model = new \app\admin\model\Cms\Communication();
//        if($this->auth->type != '1'){
//            $this->error('该账号非正常老师账号');
//        }
//        $user_info = Db::name('admin')->where(['id'=>$this->auth->id])->field('s_id,type,user_id')->find();
////        if(empty($user_id)){
////            $this->error('该账号非正常老师账号');
////        }
////        var_dump($this->user_id);
//        $zd_user_info =  Db::name('zd_user')->where(['user_id'=>$user_id])->field('user_id,school_id')->find();
//        if(empty($zd_user_info)){
//            $this->error('账号信息有误，请核对后重试');
//        }
        $this->user_id =  $this->auth->user_id;
        $this->school_id = $this->auth->s_id;
    }

    public function index()
    {;
        $this->searchFields = 'name';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //   $this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,2);

            $count=$this->model
                ->where($where)
                ->count();
            $list=$this->model
                ->where($where)
                ->order('sort desc,id asc')
                ->limit($offset,$limit)
                ->select();
            $sql = $this->model->getLastSql();

            foreach ($list as $w=>&$v){
                $v['city_num'] = $this->city_model->where(['province_id' => $v['id'],'is_del'=>0])->count();
                $v['region_num'] = $this->city_region_model->where(['province_id' => $v['id'],'is_del'=>0])->count();
            }
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);
            return json($result);
        }
//        $this->assign('pid',$pid);
//        $this->assign('province',$province);
        return $this->view->fetch();
    }
    public function edit($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
//                    $params['update_time'] = time();
//                    $params['admin_id'] = $this->auth->id;
//                    Db::name('province_city_region')->where(['city_id'=>$ids])->update(['city'=>$params['city'],'update_time'=>time()]);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        $row=$this->model->field('school_id,province_id,province,school_name')->where(['school_id'=>$school_id])->find();
//        if($row){
//            $province_id= $row['province_id'];
//        }
//        $this->assign('row',$row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /*
     * 市区
     */
    public function city()
    {
      //  $this->searchFields = 'city,province';
        $this->request->filter(['strip_tags']);
        $pid=input('province_id');
        $m_id= $this->auth->id;
        if ($this->request->isAjax()) {
            //   $this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con =[];
            if($pid){
                $con =[
                    'province_id'=>$pid,
                    'is_del'=>0
                ];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $count=$this->city_model
                ->with(['admin'])
                ->where($where)
                ->where($con)
                ->count();
            $list=$this->city_model
                ->with(['admin'])
                ->where($where)
                ->where($con)
                ->order('id asc')
                ->limit($offset,$limit)
                ->select();
            $sql = $this->city_model->getLastSql();

            foreach ($list as $w=>&$v){
                $v['region_num'] = $this->city_region_model->where(['city_id' => $v['id'],'is_del'=>0])->count();
                $v->getRelation('admin')->visible(['nickname']);
            }
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);
            return json($result);
        }
        $this->assignconfig('pid',$pid);
        return $this->view->fetch();
    }


    /*
    * 添加市区
    */
    public function add_city(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['create_time'] = time();
            $params['update_time'] = time();
            $params['admin_id'] = $this->auth->id;
            $params['province'] = get_province_name($params['province_id']);
            $res = $this->city_model->insert($params);
            if ($res){
                $this->success();
            }
            $this->error();
        }
        $province_id = input('province_id');
        $this->assign('province_id',$province_id);
        return $this->view->fetch('');
    }


    public function edit_city($ids=''){
        $row = $this->city_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['update_time'] = time();
                    $params['admin_id'] = $this->auth->id;
                    Db::name('province_city_region')->where(['city_id'=>$ids])->update(['city'=>$params['city'],'update_time'=>time()]);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        $row=$this->model->field('school_id,province_id,province,school_name')->where(['school_id'=>$school_id])->find();
//        if($row){
//            $province_id= $row['province_id'];
//        }
//        $this->assign('row',$row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /*
     * 县级
     */
    public function region()
    {
        //  $this->searchFields = 'city,province';
        $this->request->filter(['strip_tags']);
        $pid=input('city_id');
        if ($this->request->isAjax()) {
            //   $this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con =[];
            if($pid){
                $con =[
                    'city_id'=>$pid,
                    'is_del'=>0
                ];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $count=$this->city_region_model
                ->with(['admin'])
                ->where($where)
                ->where($con)
                ->count();
            $list=$this->city_region_model
                ->with(['admin'])
                ->where($where)
                ->where($con)
                ->order('id asc')
                ->limit($offset,$limit)
                ->select();
            $sql = $this->city_region_model->getLastSql();

            foreach ($list as $w=>&$v){
                $v['province'] = $this->model->where(['id' => $v['province_id'],'is_del' => 0])->value('name');
                $v['city'] = $this->city_model->where(['id' => $v['city_id'],'is_del' => 0])->value('city');
                $v->getRelation('admin')->visible(['nickname']);
            }
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);
            return json($result);
        }
        $this->assignconfig('pid',$pid);
        return $this->view->fetch();
    }

    /*
   * 添加县级
   */
    public function add_region(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $city_info = Db::name('province_city')->where(['id'=>$params['city_id']])->find();
            $params['create_time'] = time();
            $params['update_time'] = time();
            $params['province'] = get_province_name($city_info['province_id']);
            $params['city'] = $city_info['city'];
            $params['admin_id'] = $this->auth->id;
            $params['province_id'] = $city_info['province_id'];
            $res = $this->city_region_model->insert($params);
            if ($res){
                $this->success();
            }
            $this->error();
        }
        $province_id = input('city_id');
        $this->assign('city_id',$province_id);
        return $this->view->fetch('');
    }


    public function edit_region($ids=''){
        $row = $this->city_region_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['admin_id'] = $this->auth->id;
                    $params['update_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        $row=$this->model->field('school_id,province_id,province,school_name')->where(['school_id'=>$school_id])->find();
//        if($row){
//            $province_id= $row['province_id'];
//        }
//        $this->assign('row',$row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del_city($ids=''){
        $row = $this->city_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $updata = [
            'is_del'=>1,
            'update_time'=>time(),
            'admin_id'=>$this->auth->id,
        ];
        $res = $this->city_model->where(['id'=>$ids])->update($updata);
        if($res){
            $this->success('删除成功');
        }
        $this->error();
    }


    public function del_region($ids=''){
        $row = $this->city_region_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $updata = [
            'is_del'=>1,
            'update_time'=>time(),
            'admin_id'=>$this->auth->id,
        ];
        $res = $this->city_region_model->where(['id'=>$ids])->update($updata);
        if($res){
            $this->success('删除成功');
        }
        $this->error();
    }


    public function import()
    {
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1'); //内存 无限
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->Collegial_model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            // var_dump($allRow);
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
          //  var_dump($fields);
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $cell = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow);
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if($cell->getDataType() == DataType::TYPE_NUMERIC){
                        $cellstyleformat  =$cell->getStyle($cell->getCoordinate())->getNumberFormat();
                        $formatcode = $cellstyleformat->getFormatCode();
                        if(preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i',$formatcode)){

//                            $data=$val;//从excel导入后的时间
//                            $t = 24 * 60 * 60;
//                            $last_time = gmdate('Y-m-d H:i:s', ($data - 25569) * $t);
//                            var_dump($last_time);
                            $toTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($val);
                            $num = 8*60*60;
                            $toTimestamp = $toTimestamp - $num;
                            $val = date("Y-m-d H:i:s", $toTimestamp );
                            $val = strtotime($val);

                        }
                    }
                    // var_dump($val);
                    $values[] = is_null($val) ? '' : $val;
                }
             //   var_dump($values);
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
//                        $new_where = [
//                            'school_name'=>$row['school_name'],
//                            'zy_name'=>$row['zy_name'],
//                            'pc'=>$row['pc'],
//                            'kl_name'=>$row['kl_name'],
//                        ];
//                        $update_data = [
//                            'lq_num2'=>$row['lq_num'],
//                            'letter2'=>$row['letter'],
//                            'letter_flag2'=>$row['letter_flag'],
//                            'pjf2'=>$row['pjf'],
//                            'update_time'=>time()
//                        ];
//                        $re = DB::name('cs_zy')->where($new_where)->update($update_data);
//                        if($re){
//                            unset($row[$fieldArr[$k]]);
//                        }
                    }
                }
              //  var_dump($row['zy_name']);
//                $zy_name = explode('(',$row['zy_name']);
//                $zy_names = explode($zy_name[0],$row['zy_name']);
//                $row['zy_name'] = $zy_name[0];
//                $row['cs_zy_name'] = $zy_names[1];
//                $cs_arr = '';
//                foreach ($zy_name as $w=>$v){
//                    if($w==0){
//                        $row['zy_name']  = $v;
//                    }else{
//                        $cs_arr .= $v;
//                    }
//                }
                //$row['cs_name'] = $cs_arr;
                //    var_dump($zy_name);exit;
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage().$exception->getLine());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
         //   var_dump($insert);
            foreach ($insert as $w=> &$val) {
                 $common_data = $val;
                $localAppData = Db::name('school_z')->where(['id'=>$val['id']])->find();
                $log = '';
                foreach($localAppData as $key => $v){
                    foreach ($common_data as $keys =>$vs){

                        if($key == 'school'  && $keys=='school'){
//                            var_dump($key);
//                            var_dump($v);
//                            var_dump($keys);
//                            var_dump($vs);
                        }
                        if($key == $keys && $v !=$vs ){
                            $log .= $key.'由'.$v.'更新为'.$vs.'--';
                            $update = [
                                $keys=>$vs
                            ];
                            $localAppData = Db::name('school_z')->where(['id'=>$val['id']])->update($update);
//                            var_dump($keys);
//                            var_dump($vs);
                        }
                    }

                }
                if($log != ''){
                    $log_data = [
                        'log'=>$log,
                        'school_id'=>$val['id'],
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                    Db::name('school_update_log')->insert($log_data);
                }

            }


////            var_dump(count($insert));
////            var_dump($insert);exit;
//
          //  $insert = array_values($insert);
         //   $this->Collegial_model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /*
   * 县级
    */
    public function cs_vue()
    {
        //  $this->searchFields = 'city,province';
        $this->request->filter(['strip_tags']);
        $pid=input('city_id');
        if ($this->request->isAjax()) {
            //   $this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con =[];
            if($pid){
                $con =[
                    'city_id'=>$pid,
                    'is_del'=>0
                ];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $count=$this->city_region_model
                //  ->with(['province'])
                ->where($where)
                ->where($con)
                ->count();
            $list=$this->city_region_model
                //   ->with(['province'])
                ->where($where)
                ->where($con)
                ->order('id asc')
                ->limit($offset,$limit)
                ->select();
            $sql = $this->city_region_model->getLastSql();

            foreach ($list as $w=>&$v){
                $v['province'] = $this->model->where(['id' => $v['province_id'],'is_del' => 0])->value('name');
                $v['city'] = $this->city_model->where(['id' => $v['city_id'],'is_del' => 0])->value('city');
            }
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);
            return json($result);
        }
        $this->assignconfig('pid',$pid);
        return $this->view->fetch();
    }
}
